package lhd.mybatis_simple_log.actions;

import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.ui.JBColor;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBScrollPane;
import lhd.mybatis_simple_log.icons.MybatisSimpleLogIcons;
import lhd.mybatis_simple_log.utils.LogUtil;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;

/**
 * 弹窗展示sql语句
 *
 * @author lhd
 * @since 2025/6/11 10:06
 */
public class ShowSqlAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        // 获取编辑器实例
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        if (editor == null) return;

        // 获取选中文本
        String selectedSqlLog = editor.getSelectionModel().getSelectedText();
        if (selectedSqlLog == null || selectedSqlLog.isEmpty()) return;

        // 创建弹窗内容
        JPanel panel = new JPanel(new BorderLayout(5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 解析日志
        String parseSql = null;
        try {
            // 解析日志
            parseSql = LogUtil.parsingLogToSql(selectedSqlLog);
        } catch (Exception ex) {
            Messages.showMessageDialog("The log parsing failed. Please check whether the selected log content is right", "Tips", Messages.getWarningIcon());
            return;
        }

        // 文本显示区域
        JTextArea textArea = new JTextArea(parseSql);
        textArea.setEditable(true);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        // 设置背景为白色，字体为灰色
        textArea.setBackground(JBColor.WHITE);
        textArea.setForeground(JBColor.BLACK);
        textArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
        textArea.setCaretPosition(0);

        JBScrollPane scrollPane = new JBScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(700, 400));

        // 复制按钮
        JButton copyButton = new JButton("Copy");
        // 关闭按钮
        JButton closeButton = new JButton("Close");
        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(copyButton);
        buttonPanel.add(closeButton);

        // 将组件添加到面板
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 创建并显示弹窗
        JBPopup popup = JBPopupFactory.getInstance()
                .createComponentPopupBuilder(panel, null)
                .setTitle("Sql Viewer")
                .setResizable(true)
                .setMovable(true)
                .setRequestFocus(true)
                .setCancelOnClickOutside(false) // 设置点击外部不关闭弹窗
                .createPopup();

        // 关闭按钮监听
        closeButton.addActionListener(event -> {
            // 关闭弹窗
            if (!popup.isDisposed()) {
                popup.closeOk(null);
            }
        });

        // 复制按钮监听
        copyButton.addActionListener(event -> {
            // 获取文本框中的文本
            String selectedText = textArea.getText();
            if (selectedText!= null &&!selectedText.isEmpty()) {
                // 复制到剪贴板
                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                clipboard.setContents(new StringSelection(selectedText), null);

                // 提示复制成功
                JBPopupFactory.getInstance()
                       .createBalloonBuilder(new JLabel("Copied!"))
                       .setFadeoutTime(1500)
                       .createBalloon()
                       .show(RelativePoint.getCenterOf(copyButton), Balloon.Position.below);
            }
        });

        // 显示在屏幕中央（使用IDE的主窗口作为参考）
        Project project = e.getProject();
        if (project != null) {
            // 在IDE主窗口中央显示
            popup.showCenteredInCurrentWindow(project);
        } else {
            // 备选方案：在编辑器组件中央显示
            popup.showInCenterOf(editor.getContentComponent());
        }
    }

    @Override
    public void update(AnActionEvent e) {
        // 仅在选中文本时显示菜单项
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        e.getPresentation().setIcon(MybatisSimpleLogIcons.ICON);
        e.getPresentation().setEnabled(
                editor != null
                        && editor.getSelectionModel().hasSelection()
                        && editor.getSelectionModel().getSelectedText() != null
                        && LogUtil.isMybatisSqlLog(editor.getSelectionModel().getSelectedText())
        );
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return ActionUpdateThread.EDT;
    }

}
